//
//  SHPhotoBrowserLayout.m
//  Tradeaider
//
//  Created by 王方伟 on 2017/7/12.
//  Copyright © 2017年 Shinyhub. All rights reserved.
//

#import "SHPhotoBrowserLayout.h"

@interface SHPhotoBrowserLayout ()
/** 一页宽度，算上空隙 */
@property (assign, nonatomic) CGFloat pageWidth;
/** 一上次页码 */
@property (assign, nonatomic) CGFloat lastPage;
/** 最小页码 */
@property (assign, nonatomic) CGFloat minPage;
/** 最大页码 */
@property (assign, nonatomic) CGFloat maxPage;
@end

@implementation SHPhotoBrowserLayout


- (instancetype)init{
    self = [super init];
    if (self) {
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}

- (CGFloat)pageWidth{
    return self.itemSize.width + self.minimumLineSpacing;
}

- (CGFloat)maxPage{
    CGFloat contentWidth = self.collectionView.contentSize.width;
    if (contentWidth) {
        contentWidth += self.minimumLineSpacing;
        return contentWidth / self.pageWidth - 1;
    }
    return 0;
}

- (CGFloat)lastPage{
    CGFloat offsetX = self.collectionView.contentOffset.x;
    if (offsetX) {
       return round(offsetX / self.pageWidth);
    }
    return 0.f;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
    CGFloat page = round(proposedContentOffset.x / self.pageWidth);
    // 处理轻微滑动
    if (velocity.x > 0.2) {
        page += 1;
    }else if (velocity.x < -0.2){
        page -= 1;
    }
    
    // 一次滑动不允许超过一页
    if (page > self.lastPage + 1) {
        page = self.lastPage + 1;
    }else if (page < self.lastPage - 1){
        page = self.lastPage - 1;
    }
    
    if (page > self.maxPage) {
        page = self.maxPage;
    }else if (page < self.minPage){
        page = self.minPage;
    }
    self.lastPage = page;
    return CGPointMake(page * self.pageWidth, 0);
    
}
@end
